import { defineStore } from 'pinia'
import { userInfo, login ,getOauth } from '@/api/login';
import cache from '@/utils/cache';
import { ElMessage } from "element-plus";

export const userStore = defineStore('userStore', {
	state: () => ({
		user: {
			id: "",
			userName: "",
			userType: "",
		},
		token: cache.getToken()
	}),
	actions: {
		setUser(val) {
			this.user = val;
		},
		setToken(val) {
			this.token = val;
			cache.setToken(val);
		},
		// // 用户登录
		async loginAction(loginForm) {
			const res = await login(loginForm);
			if (res.success) {
				this.setToken(res.data.token);
			} else {
				ElMessage.error(res.msg || "登录出错，请重试");
			}
			return res;
		},
		//Oauth 登录
		async oauthLogin(params) {
			const res = await getOauth(params);
			if (res.success) {
				this.setToken(res.data.token);
			}
			return res;
		},
		// 获取用户信息
		async getUserInfoAction() {
			return new Promise((resolve, reject) => {
				userInfo().then((res) => {
						if (res.success) {
							this.setUser(res.data);
						} else {
							ElMessage.error(res.msg || "登录出错，请重试");
						}
						resolve(res);
					})
					.catch((error) => {
						reject(error);
					})
			})
		},
		// 用户退出
		async logoutAction() {
			// 移除 token
			this.setToken(null);
		}
	}
})
